# -*- coding: utf-8 -*-
'''
Created on 19/ott/2009

@author: sax
'''

from testapp.models import Author2, Book
from django.contrib import admin
from django.conf.project_template.urls import urlpatterns
admin.autodiscover()
from testapp.tests.basetest import AdminTestCase
import logging
import xadmin
from django.contrib.admin import TabularInline, StackedInline

class XModelAdminTest(xadmin.admin.XModelAdmin):
    pass

class TestBookInline(StackedInline):
    model = Book
    verbose_name_plural = "Books"
    extra = 2
    collapse = True
    orderable = True

class XAdminTestCase(AdminTestCase):
    model = Author2
    fixtures = ['initial_data',]
    def __init__(self, methodName='runTest'):
        from django.contrib.admin.sites import NotRegistered
        # we need an default instance of XModelAdmin
        try:
            admin.site.unregister(self.model)
        except NotRegistered:
            pass
        admin.site.register(self.model, XModelAdminTest)
                
        super(XAdminTestCase, self).__init__(methodName)

    def setUp(self):
        #xadmin.admin.LOGGER.level = logging.DEBUG
        self.reset(self.admin_model)
        
    
    def reset(self, admin_model):
        admin_model.search_help_text = None
        admin_model.disabled = []
        admin_model.read_only_fields = []
        admin_model.model_link_fields = []
        admin_model.read_only = False
        admin_model.read_only_inlines = []
        admin_model.buttons = []
        admin_model.services = []
        admin_model.fk_service =  None    
        admin_model.search_help_text = None
        admin_model.filters_mapping = {}
            
    def tearDown(self):
        xadmin.admin.LOGGER.level = logging.CRITICAL
        
#
#   list views test
#
    def test_list_view_search_help_text_empty(self):
        self.admin_model.search_help_text = ""        
        ret = self._test_list()
        self.assertEqual("", ret.context["search_help_text"] )
        
    def test_list_view_search_help_text_fixed(self):
        T = u"Nome, Cognome"
        self.admin_model.search_help_text = T
        ret = self._test_list()
        self.assertEqual(T, ret.context["search_help_text"] )

    def test_list_view_search_help_text_default_no_search(self):
        self.admin_model.search_help_text = None
        ret = self._test_list()
        self.assertEqual(u'', ret.context["search_help_text"] )

    def test_list_view_search_help_text_default_with_fields(self):
        self.admin_model.search_fields = ['last_name']
        self.admin_model.search_help_text = None
        ret = self._test_list()
        self.assertEqual(u'last name', ret.context["search_help_text"] )
#
#   list views test:filters
#
    def test_list_view_filters_alphabetic_filter(self):
        self.admin_model.list_filter = ['last_name']
        ret = self._test_list()        
        self.assertTrue( isinstance( ret.context['cl'].filter_specs[0], xadmin.filterspecs.AlphabeticFilterSpec) )

    def test_list_view_filters_alphabetic_filter_1(self):
        self.admin_model.list_filter = ['last_name']
        ret = self._test_list("?last_name__istartswith=A")        
        self.assertTrue( isinstance( ret.context['cl'].filter_specs[0], xadmin.filterspecs.AlphabeticFilterSpec) )

    def test_list_view_filters_date_range_filter_1(self):
        self.admin_model.list_filter = ['born']
        ret = self._test_list()        
        self.assertTrue( isinstance( ret.context['cl'].filter_specs[0], xadmin.filterspecs.DateRangeFilterSpec) )

    def test_list_view_filters_date_range_filter_from(self):
        self.admin_model.list_filter = ['born']
        ret = self._test_list("?&born__gte=2009-10-19")        
        self.assertTrue( isinstance( ret.context['cl'].filter_specs[0], xadmin.filterspecs.DateRangeFilterSpec) )

    def test_list_view_filters_date_range_filter_to(self):
        self.admin_model.list_filter = ['born']
        ret = self._test_list("?&born__lte=2009-10-19")        
        self.assertTrue( isinstance( ret.context['cl'].filter_specs[0], xadmin.filterspecs.DateRangeFilterSpec) )

    def test_list_view_filters_date_range_filter_from_to(self):
        self.admin_model.list_filter = ['born']
        ret = self._test_list("?&born__gte=1500-10-19&born__lte=2009-10-19")        
        self.assertTrue( isinstance( ret.context['cl'].filter_specs[0], xadmin.filterspecs.DateRangeFilterSpec) )

#
#   list views test:buttons
#

    def test_list_view_add_button_1(self):
        self.admin_model.buttons = [xadmin.admin.XModelAdminButton("label","link")]
        ret = self._test_list()        
        self.assertTrue( isinstance( ret.context['buttons'][0], xadmin.admin.XModelAdminButton) )
        
#    def test_list_view_add_button_2(self):
#            
#        def create_button(request):
#            return xadmin.admin.XModelAdminButton("label","link")
#
#        
#        from django.contrib.admin import AdminSite
#        from django.conf.urls.defaults import patterns, include
#        
#        XModelAdminTest.buttons = [create_button]   
#        class X(XModelAdminTest):
#            buttons = [create_button]
#
#        a = AdminSite("admin", "admin")
#        a.register( self.model, X )
#
#        class urlconf(object):
#            urlpatterns = patterns('',(r'^aa/', include(a.urls)))
#            
#            
#        #XModelAdminTest.buttons = [create_button]        
#        self.admin_site = a
##        u = urlconf()        
##        u.urlpatterns = a.get_urls()
##        self.urlconf = u
##        self._urlconf_setup()
#        
#        import django.contrib.admin.views.main
#        view_name = self._get_view_name("changelist")
#        url = self._reverse( view_name, current_app=a )                
#        ret = self.get_secured( url  )
#        self.assertTrue( isinstance(ret.context['cl'], django.contrib.admin.views.main.ChangeList)) 
#
#        
#        self.assertTrue( isinstance( ret.context['buttons'][0], xadmin.admin.XModelAdminButton) )
        
        

    def test_list_view_add_button_3(self):
        self.admin_model.buttons = ["testapp_author_changelist"]
        ret = self._test_list()        
        self.assertTrue( isinstance( ret.context['buttons'][0], xadmin.admin.XModelAdminButton) )


#
#   edit views test
#
    def test_edit_view_read_only(self):        
        self.admin_model.read_only = True        
        ret = self._test_edit(1)
        self.assertTrue(ret.context['read_only'] )
        self.assertNotContains(ret, "<form")


    def test_edit_view_edit_plain(self):        
        ret = self._test_edit(1)        
        self.assertFalse(ret.context['read_only'] )
        self.assertContains(ret, "<form")
    
    def test_edit_view_update_record(self):
        import datetime
        TARGET_ID = 1
        pre_obj = self.model.objects.get(pk=TARGET_ID)     
        ret = self._test_edit(TARGET_ID)  
        self._test_edit_post(TARGET_ID,{"_save":"save", 'born':"1000-10-10"})
        post_obj = self.model.objects.get(pk=TARGET_ID)
        self.assertEqual(post_obj.born, datetime.date(1000,10,10) ) 
                
    def test_edit_view_post_with_read_only_field(self):        
        self.admin_model.read_only_fields = ['born']
        TARGET_ID = 1
        
        pre_obj = self.model.objects.get(pk=TARGET_ID)
        ret = self._test_edit(TARGET_ID)        
        self.assertTrue( isinstance( ret.context['adminform'].form['born'].field.widget, 
                                     xadmin.widgets.ReadOnlyWidget) )
        #inputs =  self._get_values_from_form( ret )
        self._test_edit_post(TARGET_ID,{"_save":"save", 'born':"1000-10-10"})
        post_obj = self.model.objects.get(pk=TARGET_ID)
        self.assertEqual(pre_obj.born, post_obj.born)

    def test_edit_view_post_with_model_link_field(self):        
        self.model = Book
        TARGET_ID = 1
        self.reset(self.admin_model)
        self.admin_model.model_link_fields = ['author']
        pre_obj = self.model.objects.get(pk=TARGET_ID)
        ret = self._test_edit( TARGET_ID )        
        self.assertTrue( isinstance( ret.context['adminform'].form['author'].field.widget, 
                                     xadmin.widgets.ModelLinkWidget) )
        self._test_edit_post(1,{"_save":"save", 'author':"10"})
        post_obj = self.model.objects.get(pk= TARGET_ID)
        self.assertEqual(pre_obj.author, post_obj.author)
        self.model = Author2
    
    def test_edit_view_with_inlines(self):        
        TARGET_ID = 6
        
        TestBookInline.extra = 0
        self.admin_model.inlines = (TestBookInline,)
        self.admin_model.inline_instances.append(TestBookInline(self.model, self.admin_model.admin_site) )
                                                 
        #pre_obj = self.model.objects.get(pk=TARGET_ID)                                          
        ret = self._test_edit( TARGET_ID )
        fs = ret.context['inline_admin_formsets'][0]
        # fs == django.contrib.admin.helpers.InlineAdminFormSet
        # fs.opts == TestBookInline
        # fs.formset == 'django.forms.formsets.BaseFormSet (BookFormFormSet)

        # get django.contrib.admin.helpers.InlineAdminForm
        inline_admin_form = list(enumerate(fs))[0][1]
        self.assertTrue( isinstance( fs.opts, TestBookInline ) )
        form_data = {u'first_name': u'Giovanni', u'last_name': u'Boccaccio', u'book_set-0-title': u'Decameron ', u'book_set-0-order': u'0', u'selected_tab': u'0', u'book_set-TOTAL_FORMS': u'1', u'wp_url': '', u'book_set-0-author': u'6', u'book_set-0-id': u'18', u'born': '', u'book_set-0-year': u'1348', u'book_set-INITIAL_FORMS': u'1', u'book_set-0-DELETE': '', u'book_set-0-abstract': '', u'book_set-0-slug': '', u'nationality': ''}
        self.assertEqual(self._get_values_from_form( ret ), form_data)
    
    def test_edit_view_post_read_only(self):
        self.admin_model.read_only= True
        TARGET_ID = 6
        
        pre_obj = self.model.objects.get(pk=TARGET_ID)
        ret = self._test_edit(TARGET_ID)        
        form_data = self._get_values_from_form( ret )
       
        self.assertTrue( isinstance( ret.context['adminform'].form['born'].field.widget, 
                                     xadmin.widgets.ReadOnlyWidget) )
       
        self.assertEqual(form_data, None)


    
    def test_edit_view_with_readonly_inlines(self):        
        TARGET_ID = 8
        
 
#        TestBookInline.extra = 0
#        self.admin_model.inlines = (TestBookInline,)
#        self.admin_model.read_only_inlines = (TestBookInline,)
#        self.admin_model.inline_instances.append(TestBookInline(self.model, self.admin_model.admin_site) )
#                                                 
#        #pre_obj = self.model.objects.get(pk=TARGET_ID)                                          
        ret = self._test_edit( TARGET_ID )
#        fs = ret.context['inline_admin_formsets'][0]
#        # fs == django.contrib.admin.helpers.InlineAdminFormSet
#        # fs.opts == TestBookInline
#        # fs.formset == 'django.forms.formsets.BaseFormSet (BookFormFormSet)
#
#        # get django.contrib.admin.helpers.InlineAdminForm
#        inline_admin_form = list(enumerate(fs))[0][1]
#        self.assertTrue( isinstance( fs.opts, TestBookInline ) )
#        print self._get_values_from_form( ret )        
        
        
        
        
